package com.adminx.dao;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;

import com.adminx.entity.MessageDetail;
import com.adminx.pojo.MessageDetailPojo;
import com.adminx.util.PageResults;

@Repository
public class MessageDetailDao extends BaseDao<MessageDetail, Long>{
	
	protected static Logger LOGGER = Logger.getLogger(MessageDetailDao.class); 
	
	/**
	 * 分页查找�?
	 */
	public PageResults<MessageDetailPojo> query(Integer pageIndex, Integer pageSize, Long messageId){
		
		if(pageIndex == null){
			pageIndex = 1;
		}
		if(pageSize == null){
			pageSize = 10;
		}
		
		String sql =
			"SELECT " +
			"	a.user_name receiveUserName, " +
			"	CASE d.read_status " +
			"WHEN 1 THEN " +
			"	'已读' " +
			"ELSE " +
			"	'未读' " +
			"	END readStatus " +
			"	FROM " +
			"		xx_message m, " +
			"		xx_message_detail d, " +
			"		xx_account a " +
			"	WHERE " +
			"		m.message_id = d.message_id " +
			"	AND d.receive_account_id = a.account_id " +
			"	AND m.message_id = "+messageId;
		
		String countSql =
				"SELECT count(1)" +
				"	FROM " +
				"		xx_message m, " +
				"		xx_message_detail d, " +
				"		xx_account a " +
				"	WHERE " +
				"		m.message_id = d.message_id " +
				"	AND d.receive_account_id = a.account_id " +
				"	AND m.message_id = "+messageId;
		
		return this.findPageByFetchedSql(MessageDetailPojo.class, sql, countSql, pageIndex, pageSize);
	}
	
	/**
	 * 保存推�?消息
	 */
	public void save(String accountIds, Long messageId){
		String[] accountIdsArray = accountIds.split(",");
		for (int i = 0; i < accountIdsArray.length; i++) {
			MessageDetail messageDetail = new MessageDetail();
			messageDetail.setReceiveAccountId(Long.valueOf(accountIdsArray[i]));
			messageDetail.setMessageId(messageId);
			this.save(messageDetail);
		}
	}
}
